import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class SendKey extends StatefulWidget {
  final int roomId;
  final List renter;
  const SendKey({super.key, required this.roomId, required this.renter});

  @override
  State<StatefulWidget> createState() => _SendKeyState();

}

class _SendKeyState extends State<SendKey> {
  int _sendKeyStatus = 0;
  List _lockList = [];
  List _selectList = [];
  Map _params = {
    "lockIds": [],
    "name": "",
    "renterId": null,
    "account": ""
  };

  void _getLocks() async {
    EasyLoading.show();
    Map resData = await lockApi.lockByRoomList(widget.roomId);
    EasyLoading.dismiss();
    setState(() {
      _lockList = resData["data"] ?? [];
    });
  }

  void _sendKeys() async {
    EasyLoading.show();
    Map<String, dynamic> params = {
      "account": _params["account"],
      "lockIds": _selectList.join(","),
      "name": _params["name"],
      "remoteEnable": 1,
      "startDate": "2024-11-20 16:00:00",
      "endDate": "2025-11-20 14:00:00",
    };
    await lockApi.sendKeys(params);
    EasyLoading.showToast("钥匙发送成功");
    setState(() {
      _sendKeyStatus = 1;
    });
  }


  void _toggleLock(Map lockInfo) {
    setState(() {
      if (_selectList.contains(lockInfo["lockId"])) {
        _selectList.remove(lockInfo["lockId"]);
      } else {
        _selectList.add(lockInfo["lockId"]);
      }
    });
  }

  Future<void> _changeRenter() async {
    Map? popped = await showRoundedBottomSheet(
      builder: (context) => BottomSheetSelect(
        items: widget.renter,
        compare: (item) => item["renterId"] == _params["renterId"],
        itemAsString: (item) => item["name"],
      ),
    );
    if (popped != null) {
      setState(() {
        _params["renterId"] = popped["renterId"];
        _params["name"] = popped["name"];
        _params["account"] = popped["contacts"];
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getLocks();
  }

  Widget _sendKeyResult() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Padding(
            padding: EdgeInsets.only(top: 60, bottom: 30),
            child: DecoratedBox(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(80),
                boxShadow: [BoxShadow(color: ThemeVars.colorPrimaryLight, blurRadius: 15, spreadRadius: 1)]
              ),
              child: Icon(Icons.check_circle, color: ThemeVars.colorPrimary, size: 80,),
            ),
          ),
          Text("发送成功", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),),
          SizedBox(height: 8,),
          Text("请租客使用微信小程序授权登录", style: TextStyle(fontSize: 14, color: ThemeVars.colorWarning),),
          SizedBox(height: 60,),
          Button(
            type: ButtonType.successOutline,
            onPressed: () {
              EasyLoading.showToast("需要对接微信SDK分享小程序");
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.wechat, color: ThemeVars.colorSuccess,),
                SizedBox(width: 8,),
                Text("微信分享")
              ],
            ),
          ),
          SizedBox(height: 12,),
          Button(
            onPressed: () {
              Stacker.pop();
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [Text("完成")],
            ),
          ),
        ],
      ),
    );
  }

  Widget _renderPage() {
    return ListView(
      padding: EdgeInsets.all(ThemeVars.paddingPage),
      children: [
        MenuBlock(
          title: Text("选择锁"),
          items: List.generate(_lockList.length, (index) {
            Map item = _lockList[index];
            return MenuBlockItem(
                text: "",
                showArrow: false,
                onTap: () => _toggleLock(item),
                prefix: Row(
                  children: [
                    _selectList.contains(item["lockId"])
                        ? Icon(Icons.check_box_rounded, color: ThemeVars.colorPrimary, size: 20,)
                        : Icon(Icons.check_box_outline_blank_outlined, color: ThemeVars.colorTextTer, size: 20,),
                    SizedBox(width: 12,),
                    Text(item["lockName"]),
                  ],
                )
            );
          }),
        ),
        const SizedBox(height: 12,),
        MenuBlock(
          items: [
            MenuBlockItem(
                text: "姓名",
                suffix: Text(_params["name"]),
                onTap: () {
                  _changeRenter();
                }
            ),
            MenuBlockItem(
              text: "接受者账号",
              showArrow: false,
              suffix: Text(_params["account"]),
            )
          ],
        ),
        const SizedBox(height: 30,),
        Button(
          onPressed: () {
            _sendKeys();
          },
          child: Text("发送"),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "发送钥匙",
      child: _sendKeyStatus == 0
          ? _renderPage()
          : _sendKeyResult(),
    );
  }

}